import FilterComponent from "../../components/filter-component";
import { Form, Input, Table, Select, Modal, Space, Button, Upload, message } from "antd"; // 引入Upload组件
import { useEffect, useState } from "react";
import ExportJsonExcel from "js-export-excel";
import dayjs from "dayjs";
import costApi from "../../api/costApi";
import baseApi from "../../api/baseApi";
import commonApi from "../../api/commonApi";
import axios  from "axios";

const { confirm } = Modal;

export default function CostList() {
  const [delIds, setDelIds] = useState([]);

  const [searchForm] = Form.useForm();

  const [isModalOpen, setIsModalOpen] = useState(false);

  const searchData = (searchForm) => {
    setFilterParams({ ...filterParams, ...searchForm })
  }

  const [editForm] = Form.useForm();

  const [filterParams, setFilterParams] = useState({
    pageNum: 1,
    pageSize: 5,
    sort: "desc",
    order: "createTime",
  });

  const [costTypes, setCostTypes] = useState([]);

  const getCostTypes = async () => {
    const data = await baseApi.getList({ type: "costType" });
    const originOptions = data.records.map((item) => {
      return {
        label: item.name,
        value: item.code,
      };
    });
    setCostTypes(originOptions);
  };

  useEffect(() => {
    getCostTypes();
  }, []);


  const [dataSource, setDataSource] = useState([]);

  const [total, setTotal] = useState(0);

  const CostTypeComp = (isFilter) => {
    const options = isFilter
      ? [{ label: "全部", value: "" }, ...costTypes]
      : costTypes;
    return (
      <Select
        style={{
          width: 120,
        }}
        options={options}
      />
    );
  }

  // 定义一个state变量，用来存储上传的文件列表
  const [fileList, setFileList] = useState([]);
  const formData = new FormData();

  const handleUpload = (options) => {
    const { file } = options;
    formData.append('file', file);
    formData.append('fileType', "txt");
    formData.append('fileName', file.name);
    commonApi.uploadFile(formData).then(res => {
      message.success("上传成功")
      // 根据后端返回的结果，更新文件列表
      console.log(res);
    })
  }


  // 定义一个自定义的移除函数，用来从文件列表中移除文件
  const handleRemove = (file) => {
    // 根据文件的uid，从文件列表中过滤掉该文件
    setFileList(fileList.filter(item => item.uid !== file.uid));
  }

  /**
   * 过滤参数发生改变,重新调用接口
   */
  useEffect(() => { getData() }, [filterParams]);

  const [isLoading, setIsLoading] = useState(false);

  /**
   * 获取列表数据
   */
  const getData = async () => {
    setIsLoading(true);
    const data = await costApi.getList(filterParams);
    data.records.forEach((item) => {
      item.key = item.costId;
    });

    setDataSource(data.records);
    setTotal(data.total);
    setIsLoading(false);
  };

  const reset = () => {
    searchForm.resetFields();
    setFilterParams({
      pageNum: 1,
      pageSize: 5,
      sort: "desc",
      order: "createDate",
    });
  };

  const handleOk = async () => {
    const data = editForm.getFieldsValue();
    await costApi.addCost(data);
    setFilterParams({ ...filterParams, pageNum: 1 })
    editForm.resetFields();
    setIsModalOpen(false)
  };
  const handleCancel = () => {
    setIsModalOpen(false);
    editForm.resetFields();
  };

  const [editId, setEditId] = useState();

  const openEdit = async (record) => {
    const data = await costApi.getByKey(record)
    setIsModalOpen(true);
    setEditId(record.costId)
    editForm.setFieldsValue(data);

  };

  const columns = [
    {
      title: "序号",
      // dataSource数组里面对应要展示的字段
      dataIndex: "costId",
      key: "costId",
      align: 'center',
      render: (text, record, index) => <a>{index + 1}</a>,
    },
    {
      title: "报关编号",
      dataIndex: "orderNo",
      align: 'center',
      key: "costId",
    },
    {
      title: "费用类型",
      dataIndex: "type",
      align: 'center',
      key: "costId",
      render: (text) => {
        return (
          <div>
            {costTypes.find((item) => item.value === text)?.label}
          </div>
        )
      }
    },
    {
      title: "更新日期",
      align: 'center',
      dataIndex: "modifyDate",
      key: "costId",
      render: (text, record) => (
        <div>
          {dayjs(text).format('YYYY-MM-DD  HH:mm:ss')}
        </div>
      )
    },
    {
      title: "操作",
      align: 'center',
      dataIndex: "id",
      render: (text, record) => (
        <Space>
          <Button onClick={() => openEdit(record)}>编辑</Button>
          <Button danger onClick={() => delByKeys(record.costId)}>删除</Button>
        </Space>
      ),
    },
  ];
  const paginationChange = (pageNum, pageSize) => {
    setFilterParams({
      ...filterParams,
      pageNum
    })
  }

  const onSelectChange = (rowKeys) => {
    setDelIds(rowKeys);
  };

  const delByKeys = (id) => {
    confirm({
      title: "确定要删除吗？",
      async onOk() {
        const ids = id ? [id] : delIds;
        await costApi.delByKeys(ids)
        setFilterParams({ ...filterParams, pageNum: 1 })
        setDelIds([])
      }
    })
  }

  const handelClickExportFile = ((dataSource) => {
    let sheetFilter = ['costId', 'orderNo', 'type']
    let option = {
      fileName: '基本信息', // 导出默认文件名
      datas: [
        {
          sheetData: dataSource, // 保存至表格的数据
          sheetName: 'sheet', // excel表格sheet默认名称
          sheetFilter: sheetFilter,
          sheetHeader: ['id', '报关编号', '费用类型'], // 表格-表头
          columnWidths: ['6', '6', '6'], // 单元格宽度
        },
      ]
    }
    var toExcel = new ExportJsonExcel(option) // 创建新的模板
    toExcel.saveExcel() // 保存
  })

  const updload = (even) => {
    console.log(121212);
    even.stopPropagation()
    commonApi.uploadFile(formData)
  }



  // 定义一个下载文件的函数
  const downloadFile = () => {
    // 发送post请求，获取文件流，传递一个请求体参数
    axios.post('/api/common/download', {id: 1,name:"张三"}, {responseType: 'blob'})
      .then(res => {
        // 将文件流转换成二进制对象，指定文件类型为Excel
        const blob = new Blob([res.data], {type: 'text/plain'});
        // const blob = new Blob([res.data], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'});
        // 将二进制对象转换成URL对象
        const url = window.URL.createObjectURL(blob);
        // 创建一个a标签，设置href属性为URL对象，设置download属性为文件名
        const link = document.createElement('a');
        link.href = url;
        link.download = 'a.txt';
        document.body.appendChild(link);
        // 触发a标签的点击事件，实现文件的下载
        link.click();
        // 删除创建的a标签和URL对象
        document.body.removeChild(link);
        window.URL.revokeObjectURL(url);
      })
      .catch(err => {
        // 处理请求错误
        console.error(err);
      })
  }
  



  return (
    <div>
      <Space>
        <Space>
          <Button onClick={getData}>刷新</Button>
          <Button type="primary" onClick={() => setIsModalOpen(true)}>新增</Button>
          <Button danger onClick={() => delByKeys()} disabled={!delIds.length}>删除</Button>
        </Space>
        <Form layout="inline" form={searchForm} onFinish={searchData}>
          <Form.Item name="type" label="费用类型">
            {CostTypeComp("filter")}
          </Form.Item>
          <Form.Item name="orderNo">
            <Input placeholder="请输入报关编号搜索">
            </Input>
          </Form.Item>
          <Space>
            <Button type="primary" htmlType="submit">搜索</Button>
            <Button onClick={() => reset()}>重置</Button>
            <Button danger onClick={() => handelClickExportFile(dataSource)} >导出</Button>
            <Button danger onClick={() => downloadFile()} >下载</Button>
          </Space>
        </Form>
        <Upload
          fileList={fileList}
          customRequest={handleUpload}
          onRemove={handleRemove}
        >
          <Button >上传文件</Button>
        </Upload>
      </Space>
      <Table
        bordered
        loading={isLoading}
        rowSelection={{
          type: "checkbox",
          onChange: onSelectChange,
        }}
        pagination={{
          current: filterParams.pageNum,
          pageSize: filterParams.pageSize,
          showQuickJumper: true,
          total: total,
          onChange: paginationChange
        }}
        columns={columns}
        dataSource={dataSource}
      >
      </Table>
      <Modal title={editId ? "编辑" : "新增"} open={isModalOpen} onOk={handleOk} onCancel={handleCancel} >
        <Form form={editForm} >
          <Form.Item name="costId" label="主键" hidden>
            <Input />
          </Form.Item>
          <Form.Item name="orderNo" label="报关编号">
            <Input />
          </Form.Item>
          <Form.Item name="type" label="费用类型">
            {CostTypeComp()}
          </Form.Item>
        </Form>
      </Modal>


    </div>
  )
}